package cn.cdeden.common.core.utils;

import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * OkHttp3 HTTP请求类
 *
 * @author Nick
 */
public class OkHttp3Utils {
    private static final OkHttpClient client = new OkHttpClient();  // OkHttpClient 实例

    // 发送 GET 请求
    public static String get(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    /**
     * 发送 multipart/form-data 请求，支持文件和 JSON 数据
     *
     * @param url       请求 URL
     * @param headers   请求头
     * @param formData  表单数据（包含文件和 JSON 数据）
     * @return 响应的 JSON 字符串
     * @throws IOException
     */
    public static String postMultipart(String url, Map<String, String> headers, Map<String, Object> formData) throws IOException {
        // 创建 MultipartBody.Builder 来构建请求体
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM);  // 设置请求体类型为 FORM（multipart/form-data）

        // 添加 JSON 数据
        if (formData.containsKey("data")) {
            String jsonData = (String) formData.get("data");
            bodyBuilder.addFormDataPart("data", jsonData);  // 直接添加 JSON 字符串
        }

        // 添加文件数据
        if (formData.containsKey("file")) {
            MultipartFile file = (MultipartFile) formData.get("file");
            // 确保文件有效且不为空
            if (file != null && file.getSize() > 0) {
                // 打印调试信息，查看文件信息
                System.out.println("文件名: " + file.getOriginalFilename());
                System.out.println("文件大小: " + file.getSize());

                // 将文件转换为字节流，并明确指定 MIME 类型
                RequestBody fileBody = RequestBody.create(file.getBytes(), MediaType.parse("application/octet-stream"));
                bodyBuilder.addFormDataPart("file", file.getOriginalFilename(), fileBody);  // 将文件添加到请求体
            } else {
                throw new IOException("上传的文件为空或无法读取");
            }
        }

        // 构建 MultipartBody 请求体
        MultipartBody requestBody = bodyBuilder.build();

        // 创建 OkHttp 请求
        Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // 构建请求
        Request request = requestBuilder.build();

        // 执行请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                // 输出调试信息
                System.out.println("请求失败: " + response.code());
                System.out.println("响应体: " + response.body().string());
                throw new IOException("请求失败: " + response.code());
            }
        }
    }

    // 发送 POST 请求，传递 JSON 数据
    public static String postJson(String url, String jsonBody, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request.Builder requestBuilder = new Request.Builder().url(url).post(body);

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    // 发送 POST 请求，传递表单数据
    public static String postForm(String url, Map<String, String> formData, Map<String, String> headers) throws IOException {
        FormBody.Builder formBodyBuilder = new FormBody.Builder();

        // 添加表单数据
        if (formData != null) {
            for (Map.Entry<String, String> entry : formData.entrySet()) {
                formBodyBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        RequestBody body = formBodyBuilder.build();

        Request.Builder requestBuilder = new Request.Builder().url(url).post(body);

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    // 发送 PUT 请求
    public static String putJson(String url, String jsonBody, Map<String, String> headers) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request.Builder requestBuilder = new Request.Builder().url(url).put(body);

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

    // 发送 DELETE 请求
    public static String delete(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(url).delete();

        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string();  // 返回响应体内容
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }

}
